// 
//  featurette_tabs.js
//  /scripts
//  
//  Created by Sean Sullivan
//  Copyright 2008 Sean. All rights reserved.
// 

/**
 *
 * Structure of a widget instance.
 *
 */
OP.widget.featuretteTabs = (function(){
	// private properties
	var _widget_id = null, // id of widget.  Equal to widget's %i% or $number in PHP
		_untilnext = 10, // counter for transition
		_total_tabs = 0,
		_current_id = 1, // id of current tab
		_old_feature = null, // store previous feature as object
		_current_feature = null, // store current feature as object
		_feature_timer=null, // reference to setInterval,
		_transition_type = 'none', // default transition is 'none'
		_to_scroll,
		_event = null;
		
	/**
	 * displayTab
	 * 
	 **/
	var displayTab = function(){
		var elem = document.getElementById('op_featurette_tabs_datasets-'+_widget_id),
			elems = elem.getElementsByTagName('div'),
			tab_elems = document.getElementById('op_featurette_tabs_tabs-'+_widget_id).getElementsByTagName('li'),
			i, j,
			thisId,
			classbase;
		
		if(_current_feature) _old_feature = _current_feature; // Remember what the last feature was
		
		// Handle datasets.  Show active by hiding all not selected with css class "hide"
		for(i=0; i < elems.length; i++){
			if(elems[i].className=='oneup' || elems[i].className=='twoup') continue; // skip over the oneup and two up div elements
			
			thisId = elems[i].className.split(' ')[0].split('-')[1]; // get id dataset[i]
			
			if(!_current_feature && thisId == 1)
				_old_feature = elems[i];
			
			classbase = 'tabbed_dataset-'+thisId;
			if(thisId == _current_id){
				_current_feature = elems[i];
				
				// Send to appropriate animation
				if(_transition_type == 'none'){
					switchContent();
				}
				else
					startFader();
			}
		}
		
		// Adjust height
		elem.style.height = _current_feature.offsetHeight+'px';
		
		// Handle tabs.  Show selected tab by adding css class "selected"
		for(j=0; j < tab_elems.length; j++){
			thisId = tab_elems[j].className.split(' ')[0].split('-')[1]; // get id of tab[j]
			classbase = 'tabbed_tab-'+thisId;
			tab_elems[j].className = thisId != _current_id ? classbase : classbase+ ' selected';
		}
		
	}
	
	/**
	 * Standard method of switching tabs with no effect
	 **/
	var switchContent = function(){
		_current_feature.className = _current_feature.className;
		_current_feature.className = _current_feature.className.replace(/(\s)*hide/,'');
		_old_feature.className = _old_feature.className + ' hide';
	}
	
	/**
	 * startFader
	 * Adjust CSS and initialize process that fades from one tab to the next
	 **/
	var startFader = function(){
		_current_feature.className = _current_feature.className.replace(/(\s)*hide/,''); // Remove hide class from feature
		
		// Have to adjust CSS styles to properly stack content on top of each other
		_old_feature.style.zIndex = 2;
		
		_current_feature.style.position = 'absolute';
		_current_feature.style.top = 0;
		_current_feature.style.left = 0;
		_current_feature.style.zIndex = 1;
		
		// Mozilla and IE do opacity differently
		typeof _current_feature.style.opacity == "string" ? _current_feature.style.opacity = 1 : _current_feature.style.filter = 'alpha(opacity=100)';

		_to_scroll = 100; // how many % of opacity to scroll
		_scroller = setInterval(fade, 100); // fade every 100ms
	}
	
	/**
	 * fade
	 * Process fading
	 **/
	var fade = function(){
		if(_to_scroll == 0){
			clearInterval(_scroller); // stop process
			_current_feature.style.zIndex = 2; // new feature needs to be on top
			_old_feature.style.zIndex = 0; // old feature lands on bottom
			// Mozilla and IE do opacity differently
			typeof _old_feature.style.opacity == "string" ? _old_feature.style.opacity = 0 : _old_feature.style.filter = 'alpha(opacity=0)';
		}
		else{
			_to_scroll -= 5; // increment scroll
			// Mozilla and IE do opacity differently
			typeof _old_feature.style.opacity == "string" ? _old_feature.style.opacity = _to_scroll/100 : _old_feature.style.filter = 'alpha(opacity=' + _to_scroll + ')';
		}
	}
	
	/**
	 * processFeaturette
	 * Process automatic progression through tabs
	 **/
	var processFeaturette = function(){
		// _untilnext keeps track of increments before switching to next tab
		if(_untilnext == 0){
			// goto next tab, or back to first if there is not a next
			_current_id = parseInt(_current_id)+1 > _total_tabs ? 1 : parseInt(_current_id)+1;
			displayTab();
			_untilnext = 10;
		}
		else{
			_untilnext--;
		}
	}
	
	return{
		// build an array of all of the tabs on the page to setup event listeners
		construct: function(tabs){
			var elems = tabs.getElementsByTagName('li'),
				i,
				matched = [], // array of parentNodes without whitespace
				current = tabs['parentNode'],
				links;
			
			_total_tabs = elems.length;
			for(i=0; i < _total_tabs; i++){
				// call function when tab is clicked
				OP.utility.observe(elems[i],'click',this.switchTab);
			}
			
			/******************************************/
			//         For pause/play control
			/*****************************************/
			
			// Clean whitespace and get array of parentNodes
			while ( current && current != document ) {
				if ( current.nodeType == 1 )
					matched.push( current );
				current = current['parentNode'];
			}

			links = matched[0].getElementsByTagName('a'); // get pause/play button element
			for(i=0; i < links.length; i++){
				if(links[i].className == 'op_featurette_tabs_control'){
					OP.utility.observe(links[i],'click',this.switchPlayControl); // setup listener for play control					
				}
			}
			/*************************************/
			// End for pause/play control
			/*************************************/

			_widget_id = tabs.id.split('-')[1]; // store widget_id for later use
			
			
			// Initialize first tab by adjusting container's heigh properly and switching element position to absolute
			// This is required for crossfading effect
			datasets_elem = document.getElementById('op_featurette_tabs_datasets-'+_widget_id);
			datasets_elem.style.height = datasets_elem.getElementsByTagName('div')[0].offsetHeight+'px';
			datasets_elem.getElementsByTagName('div')[0].style.position = 'absolute';
			
			// Start a little behind so if there's two they aren't completely in sync, that would just look weird =)
			if(!document.getElementById('no_autoplay-'+_widget_id) && _total_tabs > 1) setTimeout(this.startFeaturette,Math.random()*500);
			
			return _widget_id; // return widget_id so featuretteTabs can use it as array key
		},
		
		/**
		 * switchPlayControl
		 * When user clicks pause/play control
		 */
		switchPlayControl: function(){
			var target = this.id == undefined ? event.srcElement : this,
				matched = [],
				current = target['previousSibling'],
				widget_id,
				_this;
				
			while ( current && current != document ) {
				if ( current.nodeType == 1 )
					matched.push( current );
				current = current['previousSibling'];
			}
			
			widget_id = matched[0].id.split('-')[1];

			_this = OP.widget.collection.getWidgetInstance(widget_id); // reference to the object
		
			// we are paused, stop featurette progression
			if(target.className.indexOf('paused') == -1){
				target.className = target.className + ' paused';
				_this.stopFeaturette();
			}
			// we are UNpaused, start featurette progression
			else{
				target.className = target.className.replace(/(\s)*paused/,''); // remove 'paused' class
				_this.startFeaturette();
			}
			
			return false; // return false to prevent #
		},
		
		startFeaturette: function(){
			_feature_timer = setInterval(processFeaturette,500); // execute every 500ms
		},
		
		stopFeaturette: function(){
			clearInterval(_feature_timer); // remove process
		},
		
		resetFeaturette: function(){
			_untilnext = 10;	// when user manually clicks a tab, reset
		},
		
		setId: function(newId){
			_current_id = newId;
		},
		
		switchTab: function(){
			var tmp = this.id == undefined ? event.srcElement : this, // get event target.  this won't have an id in IE
				newId = tmp.className.split(' ')[0].split('-')[1],
				matched = [],
				current = tmp['parentNode'],
				_this;
				
			// Handling whitespace trick taken from jQuery
			while ( current && current != document ) {
				if ( current.nodeType == 1 )
					matched.push( current );
				current = current['parentNode'];
			}
			
			// get widget_id from event target element
			_this = OP.widget.collection.getWidgetInstance(matched[1].id.split('-')[1]);
			
			_this.resetFeaturette();
			
			if(newId != _current_id){
				_this.setId(newId);
				displayTab();
			}
		}
	}
});

OP.widget.collection.add(OP.widget.featuretteTabs,'op_featurette_tabs_tabs');